package qjc.p_多维动态规划;

public class p3_最长回文字符串 {
    public String longestPalindrome(String s) {
        if (s == null || s.length() < 2) {
            return s;
        }
        int start = 0;
        int maxLength = 1;
        for (int i = 0; i < s.length(); i++) {
            int len1 = middle(s, i, i);
            int len2 = middle(s, i, i + 1);
            int curMax = Math.max(len1, len2);
            if (curMax > maxLength) {
                maxLength = curMax;
                start = i - (curMax - 1) / 2;
            }
        }
        return s.substring(start, start + maxLength);
    }

    private int middle(String s, int left, int right) {
        while (left >= 0 && right <= s.length() - 1 && s.charAt(left) == s.charAt(right)) {
            left--;
            right++;
        }
        return right - left - 1;
    }

}
